#ifndef DATABASE_H
#define DATABASE_H

#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QMutex>
#include <QDebug>
class Database {
public:
    static Database& getInstance() {
        static Database instance;
        return instance;
    }

    QSqlDatabase getDatabase() const {
        return db;
    }

private:
    QSqlDatabase db;
    QMutex mutex;

    Database() {
        QMutexLocker locker(&mutex);
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("Sur.db");
        // 设置数据库连接的编码为UTF-8
        db.setConnectOptions("QSQLITE_USE_declared_TYPE=1;QSQLITE_ENABLE_REGEXP=1;QSQLITE_CODEC=UTF8");

        if (!db.open()) {
            qCritical() << "Error: connection with database failed";
        } else {
            initializeDatabase();
        }
    }

    ~Database() {
        db.close();
    }

    void initializeDatabase() {
        QSqlQuery query;
        query.exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT UNIQUE, password TEXT)");
        query.exec("CREATE TABLE IF NOT EXISTS questions (id INTEGER PRIMARY KEY, text TEXT, options TEXT)");

        query.exec("CREATE TABLE IF NOT EXISTS clientusers (id INTEGER PRIMARY KEY AUTOINCREMENT , username TEXT UNIQUE, password TEXT)");
        // 创建 submissions 表
        query.exec("CREATE TABLE IF NOT EXISTS submissions ("
                   "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                   "client_name TEXT, "
                   "submit_time TEXT, "
                   "question_id INTEGER, "
                   "answer TEXT, "
                   "FOREIGN KEY (question_id) REFERENCES questions(id)"
                   ")");
    }

    Database(const Database&) = delete;
    Database& operator=(const Database&) = delete;
};

#endif // DATABASE_H
